package com.quasar.sika.design.server.common.config;

import com.google.common.collect.Maps;
import com.sika.code.standard.db.config.ShardingDataSourceConfig;
import com.sika.code.standard.db.properties.CustomerShardingProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
/** 排除DataSourceConfiguratrion */
@ConditionalOnProperty(name = {"spring.datasource.sharding.enable"}, matchIfMissing = false, havingValue = "true")
public class SikaDesignDataSourceConfig extends ShardingDataSourceConfig {

    // 创建数据源
    // 所有引入db-core的模块都需要一个核心库，可以是user-center，也可以是oauth-center,file-center,sms-center
    @Bean
    @ConfigurationProperties("spring.datasource.hikari.master")
    public DataSource dataSourceMaster() {
        return DataSourceBuilder.create().build();
    }

    // 从数据
    @Bean
    @ConfigurationProperties("spring.datasource.hikari.slave")
    public DataSource dataSourceSlave() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.hikari.single")
    public DataSource dataSourceSingle() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dataSource")
    @Primary
    public DataSource dataSource(@Qualifier("dataSourceMaster") DataSource dataSourceMaster) {
        Map<String, DataSource> dataSourceMap = Maps.newHashMap();
        dataSourceMap.put("dataSourceMaster", dataSourceMaster);
        dataSourceMap.put("dataSourceMaster1", dataSourceMaster);
        dataSourceMap.put("sika-design-admin", dataSourceMaster);
        return buildDataSource(dataSourceMap);
    }

    @Override
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.sharding")
    protected CustomerShardingProperties getCustomerShardingProperties() {
        return new CustomerShardingProperties();
    }
}
